home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16011 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  101 lines

  1. Path: ix.netcom.com!news
  2. From: giuliano@ix.netcom.com(Giuliano Carlini)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How do I put DIFFERENT classes in the same linked list?
  5. Date: 8 Apr 1996 08:55:55 GMT
  6. Organization: Netcom
  7. Message-ID: <4kakar$i22@dfw-ixnews1.ix.netcom.com>
  8. References: <4ka938$bj6@wintermute.ecs.fullerton.edu>
  9. NNTP-Posting-Host: lbx-ca6-22.ix.netcom.com
  10. X-NETCOM-Date: Mon Apr 08  3:55:55 AM CDT 1996
  11.  
  12. In <4ka938$bj6@wintermute.ecs.fullerton.edu> grosin@titan (Gil Rosin)
  13. writes: 
  14. >
  15. >Here is the source code I have worked up so far:
  16. >
  17. >#include <iostream.h>
  18. >class A
  19. > {
  20. >  public:
  21. >    A *next;
  22. >    A *prev;
  23. >    void Print();
  24. > };
  25. >class Demo
  26. > {
  27. >  public:
  28. >    void Insert(A *Temp);
  29. >    void Insert2(A *Temp);
  30. >    void Test(void);
  31. >    A *First;
  32. > };
  33. >class B : public A
  34. > {
  35. >  void Print();
  36. > };
  37. >class C : public A
  38. > {
  39. >  void Print();
  40. > };
  41. >main()
  42. > {
  43. >  Demo *T = new Demo;
  44. >  A *Test = new B;
  45. >  T->Insert(Test);
  46. >  Test = new C;
  47. >  T->Insert2(Test);
  48. >  T->Test();
  49. >  return 0;
  50. > }
  51. >void B::Print()
  52. > {
  53. >  cout << "I am in class B" << '\n';
  54. > }
  55. >void C::Print()
  56. > {
  57. >  cout << "I am in class C" << '\n';
  58. > }
  59. >void Demo::Insert(A *Temp)
  60. > {
  61. >  First = Temp;
  62. > }
  63. >void Demo::Insert2(A *Temp)
  64. > {
  65. >  First->next = Temp;
  66. > }
  67. >void Demo::Test(void)
  68. > {
  69. >  First->Print();
  70. >  First->next->Print();
  71. > }
  72. >void A::Print()
  73. > {
  74. >  cout << "I am in class A" << '\n';
  75. > }
  76. >
  77.  
  78. Make Print() virtual:
  79.     virtual void Print();
  80.  
  81. If you don't say "virtual" in the declaration, then C++ uses the static
  82. type - that is the type you declare for the variable - to select the
  83. function to call. Since Demo::First and A::Next are declared to be A*,
  84. the compiler selects A::Print no matter what the actual type is.
  85. Declaring Print to be virtual changes all that. Virtual tells the
  86. compiler to use the actual type when selecting the Print function to
  87. use.
  88.  
  89. giuliano
  90.